<?php
try {
    // 设置响应头
    header('Content-Type: application/json; charset=utf-8');
    
    // 加载配置并连接数据库
    $config = include 'config.php';
    $pdo = new PDO("mysql:host={$config['host']};dbname={$config['name']};charset=utf8mb4", 
                   $config['user'], $config['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // GET请求：查询密码
    if ($_GET) {
        $md5 = $_GET['md5'] ?? '';
        
        // 验证MD5格式
        if (strlen($md5) !== 32 || !ctype_xdigit($md5)) {
            echo json_encode(['status' => 'error', 'message' => '无效的MD5格式']);
            exit;
        }
        
        // 使用预处理语句防止SQL注入
        $stmt = $pdo->prepare("SELECT password FROM secert WHERE file_md5 = ?");
        $stmt->execute([$md5]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result === false) {
            echo json_encode(['status' => 'not_found', 'message' => '服务器没有该文件对应的密码']);
        } else {
            echo json_encode(['status' => 'success', 'pwd' => $result['password']],JSON_UNESCAPED_UNICODE);
        }
    }
    
    // POST请求：添加密码
    elseif ($_POST) {
        $md5 = $_POST['md5'] ?? '';
        $pwd = $_POST['pwd'] ?? '';
        $filename = $_POST['file_name'] ?? '';
        
        // 验证输入
        if (strlen($md5) !== 32 || !ctype_xdigit($md5)) {
            echo json_encode(['status' => 'error', 'message' => '无效的MD5格式']);
            exit;
        }
        
        if (empty($pwd)) {
            echo json_encode(['status' => 'error', 'message' => '密码不能为空']);
            exit;
        }
        if (empty($filename)) {
            echo json_encode(['status' => 'error', 'message' => '文件名不能为空']);
            exit;
        }
        
        // 使用预处理语句防止SQL注入
        $stmt = $pdo->prepare("INSERT INTO secert (file_md5, password,file_name) VALUES (?, ?,?) 
                              ON DUPLICATE KEY UPDATE password = VALUES(password)");
        $stmt->execute([$md5, $pwd,$filename]);
        
        echo json_encode(['status' => 'success', 'message' => '密码保存成功']);
    }
    
    // 不支持的请求方法
    else {
        echo json_encode(['status' => 'error', 'message' => '不支持的请求方法']);
    }
    
} catch (PDOException $e) {
    // 数据库错误
    echo json_encode(['status' => 'error', 'message' => '数据库操作失败: ' . $e->getMessage()]);
} catch (Exception $e) {
    // 其他错误
    echo json_encode(['status' => 'error', 'message' => '系统错误: ' . $e->getMessage()]);
}
?>